<?php
    /**
     * Created by PhpStorm.
     * User: huangzhongwei
     * Date: 2018/10/24
     * Time: 18:29
     */

    namespace app\api\controller;

    use app\api\service\Token;
    use app\api\validate\IDMustBePositiveInt;
    use app\api\validate\SaveVoucher;
    use app\common\model\Voucher as VoucherModel;
    use app\lib\exception\ExistingException;
    use app\lib\exception\MissException;
    use app\lib\exception\SuccessMessage;
    use app\common\model\AccountHasVoucher;

    class Voucher extends BaseController
    {
        protected $beforeActionList = [
            'checkExclusiveScope' => ['only' => 'getaccountvouchers,getaccountvouchers'],
            'checkSuperScope'     => ['only' => 'createvoucher'],
        ];

        /**创建优惠卷
         * @return SuccessMessage
         * @throws \app\lib\exception\ParameterException
         */
        public function createVoucher()
        {
            (new SaveVoucher())->goCheck();
            $data = input('post.');
            (new VoucherModel())->save($data);
            return new SuccessMessage();
        }

        /**
         * 用户领取优惠卷
         * @return SuccessMessage
         * @throws ExistingException
         * @throws MissException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function accountGetVouchers()
        {
            (new IDMustBePositiveInt())->goCheck();
            $uid = Token::getCurrentUid();
            //判断当前优惠卷是否存在
            $voucher = (new VoucherModel())->get(input('post.id'));
            if (!$voucher) {
                throw new MissException(['msg' => '优惠卷不存在', 'errorCode' => 50001]);
            }

            $accountHasVoucher = new AccountHasVoucher();

            //判断当前用户是否拥有此优惠卷
            $isExisted = $accountHasVoucher->where(['account_id' => $uid, 'voucher_id' => input('post.id')])
                                           ->find();
            if ($isExisted) {
                throw new ExistingException(['msg' => '当前用户此优惠卷已存在', 'errorCode' => 50000]);
            }

            $accountHasVoucher->account_id = $uid;
            $accountHasVoucher->voucher_id = input('post.id');
            $accountHasVoucher->save();
            return new SuccessMessage();
        }

        /**
         * 获取当前用户优惠卷
         * @return array|\PDOStatement|string|\think\Collection
         * @throws \app\lib\exception\ParameterException
         */
        public function getAccountVouchers()
        {
            $uid = Token::getCurrentUid();
            return AccountHasVoucher::getAccountVouchers($uid);
        }


    }
